package com.esheeper.CAS.Controller;

import com.esheeper.CAS.Pojo.User;
import com.esheeper.CAS.Service.UserService;
import com.esheeper.CAS.Util.CryptUtil;
import com.esheeper.CAS.Util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * UserController
 *
 * @author Wenyang Su
 * @version 1.0.0
 * @description 处理关于用户的请求
 * @date 2023-05-16
 */
@RestController
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    CryptUtil cryptUtil;

    @Autowired
    ResponseUtil res;
    @PostMapping("/login")
    Map login(@RequestBody User user) throws NoSuchAlgorithmException {
        System.out.println(user);
        User loginedUser = userService.findUserByUsernameAndPassword(user);

        Date expires = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(expires);
        calendar.add(Calendar.DATE,1);
        expires = calendar.getTime();

        String token = cryptUtil.GenerateToken(user,expires);

        Map<String,Object> data = new HashMap<String,Object>();

        data.put("token",token);
        data.put("id",loginedUser.getId());
        data.put("username",loginedUser.getUsername());
        data.put("expires",expires);

        return res.success(data);
    }

    @PostMapping("/register")
    Map register(@RequestBody User user) throws NoSuchAlgorithmException {

        if(cryptUtil.GetPwdSecurityLevel(user.getPassword()) < cryptUtil.STRONG){
            return res.fail(ResponseUtil.REQUEST_ERROR_PASSWORD_NOT_SECURE,null);
        }
        user = userService.insertUser(user);
        return login(user);

    }

    @PostMapping("/changePassword")
    Map changePassword(@RequestBody User user) throws NoSuchAlgorithmException {

        if(cryptUtil.GetPwdSecurityLevel(user.getPassword()) < cryptUtil.STRONG){
            return res.fail(ResponseUtil.REQUEST_ERROR_PASSWORD_NOT_SECURE,null);
        }
        user = userService.updateUser(user);
        return login(user);

    }

    @PostMapping("/test")
    Map Test(@RequestBody Map<String,Date> map){
        return map;
    }

}
